/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eroshetta;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.print.PrinterJob;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 *
 * @author Administrator
 */
public class PrescriptionFrame extends javax.swing.JFrame {
        PrescriptionView presc;
       static EntityManagerFactory emf = Eroshetta.emf;
       static EntityManager em = Eroshetta.em;
       public static boolean saveFlag = false;
        
        

    /**
     * Creates new form PrescriptionFrame
     */
    public PrescriptionFrame() {
        
        initComponents();
      
         
        
    }
    public PrescriptionFrame(PrescriptionView pView)
    {
        initComponents();
        
//        this.setPreferredSize(new Dimension(300,370));
//        this.setMinimumSize(new Dimension(300,370));
        this.setLocation(400,50);
        presc = pView;
       // presc.setPreferredSize(new Dimension(380,450));
       // presc.setMinimumSize(new Dimension(380,450));
       // presc.setMaximumSize(new Dimension(380,450));
        prescContainer.setLayout(new BorderLayout());
        //presc.setBackground(Color.red);
        prescContainer.add(presc,BorderLayout.NORTH);
        //this.getContentPane().add(gridbag);
        
        
        
    }
    public JButton getPrintButton()
    {
        return this.printPresc;
    }
            

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        printPresc = new javax.swing.JButton();
        cancelPresc = new javax.swing.JButton();
        prescContainer = new javax.swing.JPanel();

        setTitle("Prescription ");
        setMinimumSize(new java.awt.Dimension(500, 550));
        setResizable(false);

        printPresc.setText("Print");
        printPresc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                printPrescActionPerformed(evt);
            }
        });

        cancelPresc.setText("Cancel");
        cancelPresc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelPrescActionPerformed(evt);
            }
        });

        prescContainer.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        prescContainer.setMaximumSize(new java.awt.Dimension(533, 556));
        prescContainer.setPreferredSize(new java.awt.Dimension(533, 556));

        javax.swing.GroupLayout prescContainerLayout = new javax.swing.GroupLayout(prescContainer);
        prescContainer.setLayout(prescContainerLayout);
        prescContainerLayout.setHorizontalGroup(
            prescContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        prescContainerLayout.setVerticalGroup(
            prescContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 554, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(prescContainer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(printPresc, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cancelPresc, javax.swing.GroupLayout.DEFAULT_SIZE, 328, Short.MAX_VALUE)
                        .addGap(18, 18, 18))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(prescContainer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(printPresc)
                    .addComponent(cancelPresc))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void printPrescActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printPrescActionPerformed
        // TODO add your handling code here:
        if(saveFlag)
        {
         
            em.getTransaction().begin();
            Prescriptions p = this.presc.getCurrentPresc();
            em.persist(p);
            em.flush();
            em.refresh(p);
            em.refresh(p.getPatientId());
            em.getTransaction().commit();
            
    //        System.out.println(p.getId());
            
            Collection<DrugTimes> dTimes = new ArrayList<DrugTimes>();
            dTimes = this.presc.getDrugTimes();
            Collection<DrugTimes>finalTimes = new ArrayList<DrugTimes>();
            for(int i=0; i<dTimes.size() ;i++)
            {
                DrugTimes dTime = (DrugTimes)dTimes.toArray()[i];
      //        System.out.println(dTime.toString());
                dTime.drugTimesPK.setPrescriptionId(p.getId());
      //        System.out.println(dTime.getPrescriptions());
                finalTimes.add(dTime);
                
                
            }

            em.getTransaction().begin();
            p.setDrugTimesCollection(finalTimes);
            em.persist(p);
            em.getTransaction().commit();
            
           
        }
        SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            try {
               
           			
               //get a PrintJob
               PrinterJob pjob = PrinterJob.getPrinterJob();
               //set a HelloPrint as the target to print
               pjob.setPrintable(presc, pjob.defaultPage());
               //get the print dialog, continue if canel
               //is not clicked
               if (pjob.printDialog()) {
                  //print the target (HelloPrint)
                  pjob.print();
               }
            } catch (Exception e) {
               e.printStackTrace();
            }
         }
      });
            Eroshetta.DrugsInPrescription.removeAll();
            Eroshetta.DrugsInPrescription.revalidate();
            Eroshetta.DrugsInPrescription.repaint();
            Eroshetta.drugsPanels.clear();
            Eroshetta.drugsCollectionInPrescription.clear();
            Eroshetta.workingOnPrescription = false;
            Eroshetta.jTextArea1.setText(null);
            this.setDefaultCloseOperation(this.HIDE_ON_CLOSE);
            this.setVisible(false);
    }//GEN-LAST:event_printPrescActionPerformed

    private void cancelPrescActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelPrescActionPerformed
        // TODO add your handling code here:
        this.setDefaultCloseOperation(this.HIDE_ON_CLOSE);
        this.setVisible(false);
    }//GEN-LAST:event_cancelPrescActionPerformed

    /**
     * @param args the command line arguments
     */
    
    
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PrescriptionFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PrescriptionFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PrescriptionFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PrescriptionFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
        
        

            public void run() {
                javax.persistence.Query q =em.createNamedQuery("Prescriptions.findById");
                q.setParameter("id", 1);
                Prescriptions p = (Prescriptions)q.getSingleResult();
                
                PrescriptionView prescView = new PrescriptionView(p);
                new PrescriptionFrame(prescView).setVisible(true);
                
                
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelPresc;
    private javax.swing.JPanel prescContainer;
    private javax.swing.JButton printPresc;
    // End of variables declaration//GEN-END:variables
}
